package com.xuln.mail.service.impl;

import java.io.IOException;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.xuln.common.freemarker.FreeMarkerService;
import com.xuln.mail.Message;
import com.xuln.mail.service.IMessageService;

import freemarker.template.TemplateException;

public class MailSenderServiceImpl implements IMessageService {
	@Resource
	private MailSender mailSender;
	@Resource
	private FreeMarkerService freeMarkerService;
	@Resource
	private Message mailMessage;

	public void sendMessage() {
		if (mailMessage != null) {
			sendMessage(mailMessage);
		}
	}

	public void sendMessage(Message message) {
		// 根据模板产生邮件内容
		if (message.getTemplateName() != null && message.getTemplateModel() != null) {
			try {
				String content = generateEmailContent(message);
				message.setContent(content);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TemplateException e) {
				e.printStackTrace();
			}
		}
		try {
			MimeMessage mimeMsg = ((JavaMailSenderImpl) mailSender).createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true, "utf-8");

			if (message.getSubject() != null) {
				helper.setSubject(message.getSubject());
			}
			if (message.getFrom() != null) {
				helper.setFrom(message.getFrom());
			}
			if (message.getRecipient() != null) {
				helper.setTo(message.getRecipient());
			} else if (message.getRecipients() != null) {
				helper.setTo(message.getRecipients());
			} else {
				// TODO
			}
			helper.setText(message.getContent(), message.isHtmlMail());
			((JavaMailSenderImpl) mailSender).send(mimeMsg);
		} catch (MessagingException ex) {
			ex.printStackTrace();
			// throw new FunctionException("邮件发送失败");
		}
	}

	public Message getDefaultMessageInfo() {
		Message message = new Message();
		message.setFrom(mailMessage.getFrom());
		message.setSubject(mailMessage.getSubject());
		message.setHtmlMail(mailMessage.isHtmlMail());
		message.setRecipient(mailMessage.getRecipient());
		message.setTemplateName(mailMessage.getTemplateName());
		return message;
	}

	public void setMessage(Message message) {
		this.mailMessage = message;
	}

	private String generateEmailContent(Message messeage) throws IOException, TemplateException {
		String content = freeMarkerService.processTemplateIntoString(messeage.getTemplateName(), messeage
				.getTemplateModel());
		return content;
	}

}
